/*
 * LoginAction
 * 
 * Version 1.0
 *
 * 7-8-08
 * 
 * Modification Logs:
 *   DATE        AUTHOR      DESCRIPTION
 *  --------------------------------------------------------
 *  9-8-08		TuHA		Tao lop
 *  14-8-08		TuHA		Cai ham execute
 */

package vn.fpt.fsoft.fcos.action;

import org.apache.struts.action.Action;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import vn.fpt.fsoft.fcos.form.LoginForm;
import vn.fpt.fsoft.fcos.bl.LoginBL;
import vn.fpt.fsoft.fcos.dao.UserDao;
import vn.fpt.fsoft.fcos.entity.UserEntity;
import javax.servlet.http.HttpSession;
import vn.fpt.fsoft.fcos.util.Constant;

/**
 * LoginAction
 * @author user
 * @version 1.0
 */
public class LoginAction extends Action {
	
	/**
	 * @param mapping is the ActionMapping object 
	 * @param form is the LoginForm object
	 * @param request is the HttpRequest object of this process
	 * @param reponse is the HttpReponse object of this process
	 * @return the ActionForward object of this action 
	 */
	public ActionForward execute (ActionMapping mapping,
		     					ActionForm form,
		     					HttpServletRequest request,
		     					HttpServletResponse response) throws Exception {
		
		// Casting form into LoginForm
		LoginForm loginForm = (LoginForm)form;
		LoginBL loginBL = new LoginBL(loginForm.getUserId(), loginForm.getPassword());
		
		// Check whether processId of loginForm is "LOGIN_000" or not
		String processId = request.getParameter("processId");
		
		if ((processId != null) &&(("LOGIN_000").compareTo(processId) != 0)) {
			
			// Otherwise, return ActionForward of "init".			
			return mapping.findForward("init");
		}
		
		// Create an instance of HttpSession form the request parameter with name "httpSession"
		HttpSession session = request.getSession();
		
		// if userId of loginForm is empty:
		if (loginForm.getUserId() == "") {
			
			// + Add into the session with a pair data (key, value): ("SK_ERRORCODE","")
			session.putValue(Constant.SK_ERRORCODE, Constant.MESSAGE_003);
			
			// + Getting ActionForward of forward name "fail"
			ActionForward forward = mapping.findForward("fail");
			
			// + Stop the process and return ActionForward of "fail"
			return forward;
		}
		
		// Calling method checkUser of LoginBL
		if (!loginBL.isAuthentication()) {
			
			return mapping.findForward("fail");
		}
		
		// Create an instance of UserEntity and put into the session with key SK_USER_ENTITY
		UserEntity userEntity = loginBL.getUserEntity();		
		
		session.putValue(Constant.SK_USER_ENTITY, userEntity);
		
		// Return ActionForward of "success"
		return mapping.findForward("success");
	}
}
